package com.kancy.kie.server.client.service;

import org.kie.api.runtime.ExecutionResults;

import java.util.*;

/**
 * <p>
 * RuleResult
 * <p>
 *
 * @author: kancy
 * @date: 2020/3/14 16:51
 **/

public class RuleResults {

    RuleResults() {
    }

    /**
     * 是否调用成功
     */
    private boolean success;

    /**
     * 返回码
     * @see org.kie.server.api.model.KieServiceResponse.ResponseType
     */
    private String code;

    /**
     * 返回描述
     */
    private String msg;

    /**
     * 执行结果数据
     */
    private transient ExecutionResults executionResults;


    public boolean isSuccess() {
        return success;
    }

    void setSuccess(boolean success) {
        this.success = success;
    }

    public String getCode() {
        return code;
    }

    void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    void setMsg(String msg) {
        this.msg = msg;
    }

    ExecutionResults getExecutionResults() {
        return executionResults;
    }

    void setExecutionResults(ExecutionResults executionResults) {
        this.executionResults = executionResults;
    }

    /**
     * 获取所有标识
     * @return
     */
    public Collection<String> getIdentifiers() {
        if (Objects.isNull(getExecutionResults())){
            return Collections.emptyList();
        }
        return getExecutionResults().getIdentifiers();
    }

    /**
     * 获取工作内存对象
     * @param identifier
     * @param <T>
     * @return
     */
    public <T> T getValue(String identifier) {
        if (Objects.isNull(getExecutionResults())){
            return null;
        }
        return (T) getExecutionResults().getValue(identifier);
    }

    /**
     * getFactHandle
     * @param identifier
     * @param <T>
     * @return
     */
    public <T> T getFactHandle(String identifier) {
        if (Objects.isNull(getExecutionResults())){
            return null;
        }
        return (T) getExecutionResults().getFactHandle(identifier);
    }


    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("RuleResult")
                .append("(")
                    .append("success=").append(isSuccess()).append(", ")
                    .append("code='").append(getCode()).append("', ")
                    .append("msg=").append(getMsg()).append(", ")
                    .append("data=").append(getData())
                .append(")");
        return builder.toString();
    }

    private Object getData() {
        Map<String, Object> data = new HashMap<>();
        if (Objects.nonNull(getExecutionResults())){
            Collection<String> identifiers = getExecutionResults().getIdentifiers();
            if (Objects.nonNull(identifiers)){
                identifiers.stream().forEach(identifier -> {
                    data.put(identifier, getValue(identifier));
                });
            }
        }
        return data;
    }
}
